import optparse
import sys

from matplotlib import pyplot
import tables

from charmicat import BadCommandLineError

def adc_vs_index(adc, index=0, output='adc_vs_index'):
    mpl = 'k. rx bo g^'.split()
    
    for col in xrange(4):
        for row in xrange(4):
            for ch in xrange(8):
                pyplot.clf()
                pyplot.figure(figsize=(8,6))
                pyplot.axes((0.175, 0.15, 0.8, 0.72))
                for win in xrange(4):
                    pyplot.plot(range(win*64, (win+1)*64),
                                adc[index][col][row][ch][win],
                                mpl[win])
                
                pyplot.xlabel("position in sample array")
                pyplot.ylabel("ADC")
                pyplot.title("ADC vs index for {}:{}:{}".format(col, row, ch))
                pyplot.savefig("{}{}{}{}.png".format(output, col, row, ch))

                sys.stdout.write("{}/{} plots done\r".format(
                        (col+1)*(row+1)*(ch+1),
                        4*4*8))

                sys.stdout.flush()

    print
            

def main():    
    '''
    btplot adc_vs_index [opts] file.h5 

    Plot the ADC value versus array index for a single event.
    '''
    
    op = optparse.OptionParser(usage=main.__doc__)
    
    op.add_option("-i", "--index", dest='index', type='int', default=0,
                  help='Plot event at index INDEX', metavar='INDEX')
    op.add_option("-o", "--output-tag", dest='output', default='adc_vs_index',
                  help='Write output files as OUTPUT[COL][ROW][CHAN].png', 
                  metavar='OUTPUT')

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = "Please supply a PyTables file as input."
        raise BadCommandLineError(msg, -1)

    with tables.openFile(args[0]) as fp:
        adc_vs_index(fp.root.adc, **vars(opts))


if __name__ == '__main__':
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)


    
